<template>
  <div class="treeSelectWapper">
    <div class="leftTreeWapper">
      <div v-if="loading" class="loadingWapper">
        <a-spin />
      </div>
      <a-select
        v-else
        class="searchInput"
        show-search
        :value="searchVal"
        :placeholder="$t('groupmanger.keyword')"
        :default-active-first-option="false"
        :show-arrow="false"
        :filter-option="false"
        :not-found-content="null"
        label-in-value
        v-model="searchVal"
        @search="fetchApply"
        @select="searchSelect"
      >
        <a-spin v-if="fetching" slot="notFoundContent" size="small" />
        <a-select-option v-for="d in searchData" :key="d">
          {{ d }}
        </a-select-option>
      </a-select>
      <div class="refreshWapper" v-if="showRefresh">
        <a-icon
          @click="refreshApplyTree"
          type="redo"
          style="font-size: 40px; color: #2b6afd; cursor: pointer"
        />
      </div>
      <a-tree
        v-else
        class="allpyTree"
        v-model="applyTree.selectedKeys"
        checkable
        :expanded-keys="applyTree.expandedKeys"
        :auto-expand-parent="applyTree.autoExpandParent"
        :tree-data="applyTree.treeData"
        @expand="onTreeExpand"
        @check="onTreeSelect"
      />
    </div>
    <div class="rightSelectWapper">
      <a-checkbox-group v-model="selectApplyName" @change="onListSelectChange">
        <a-checkbox v-for="item in selectApplyName" :key="item" :value="item"
          >{{ item.replace('WEBSITE_', '') }}
        </a-checkbox>
      </a-checkbox-group>
    </div>
  </div>
</template>
<script>
import { maccApi, requestHttp } from '@utils/index';

export default {
  name: 'applyTreeSelect',
  props: {
    gwSn: {
      type: String,
      default: () => {
        return '';
      },
    },
    selectApply: {
      type: Array,
      default: () => {
        return [];
      },
    },
    //应用/网站，默认只显示应用
    policyType: {
      type: String,
      default: () => {
        return 'BLOCK';
      },
    },
    //是否需要包装一层全部应用或者全部网站
    needAnyLevel: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
  },

  data() {
    return {
      fetching: false,
      searchData: [], //搜索结果
      searchVal: undefined,
      loading: false,
      applyTree: {
        expandedKeys: [],
        autoExpandParent: false,
        selectedKeys: [],
        treeData: [],
      },
      treeDataArr: [],
      selectApplyName: [],
      treeApplyMaps: {},
      showRefresh: false,
      blockList: [], //应用树
      webSiteList: [], //网站树
    };
  },

  components: {},

  watch: {
    policyType() {
      this.initView();
    },
    selectApply() {
      this.setSelTree();
    },
  },

  async mounted() {
    this.initView();
  },

  methods: {
    async initView() {
      await this.dealPolicyType();
      this.setSelTree();
    },
    async dealPolicyType() {
      if (this.blockList.length == 0) {
        await this.getApplyTreeData();
      }
      let blockList = [...this.blockList];
      let websiteList = [...this.webSiteList];
      let data = null;
      if (this.needAnyLevel) {
        blockList = [
          {
            app_name: this.$t('groupmanger.allApplications'),
            app_list: blockList,
          },
        ];
        websiteList = [
          {
            app_name: this.$t('groupmanger.allWebsites'),
            app_list: websiteList,
          },
        ];
      }
      //NBR设备应用和网站同时支持
      if (
        this.policyType.indexOf('BLOCK') != -1 &&
        this.policyType.indexOf('WEBSITE') != -1
      ) {
        data = [...blockList, ...websiteList];
      } else if (this.policyType.indexOf('WEBSITE') != -1) {
        data = websiteList;
      } else {
        data = blockList;
      }
      if (data) {
        this.dealMapTreeData(data);
        this.treeApplyMaps = { ...this.treeApplyMaps };
        this.applyTree.treeData = data;
      }

      if (this.$listeners.renderSuccess) {
        this.$emit('renderSuccess');
      }
    },
    setSelTree() {
      this.$nextTick(() => {
        this.applyTree.selectedKeys = [...this.selectApply];
        this.applyTree = { ...this.applyTree };
        this.selectApplyName = [...this.selectApply];
      });
    },

    //获取应用树
    async getApplyTreeData() {
      this.loading = true;
      let {
        code,
        msg = this.$t('flowControl.tip39'),
        data,
      } = await requestHttp({
        api: `${maccApi.GET_APPLY_TREE}?sn=${this.gwSn}`,
        method: 'GET',
      });
      this.loading = false;
      if (code == 25) {
        this.$message.info(this.$t('flowControl.tip40'));
        this.showRefresh = true;
        return;
      } else if (code != 0) {
        this.$message.error(msg);
        return;
      }
      this.showRefresh = false;
      this.blockList = data.app_list;
      let list = data.url_list || [];
      list.sort(function (a, b) {
        if (a.customize && b.customize) {
          return -1;
        } else if (a.customize && !b.customize) {
          return 1;
        } else {
          return -1;
        }
      });
      this.webSiteList = list;
    },

    // 格式化处理应用树节点
    dealMapTreeData(data, parent, keyIndex) {
      for (let i = 0; i < data.length; i++) {
        let key = data[i].app_name || data[i].app_type;
        data[i].value = key;

        if (
          this.policyType.indexOf('BLOCK') != -1 &&
          this.policyType.indexOf('WEBSITE') != -1
        ) {
          if (keyIndex) {
            key = keyIndex + key;
          } else if (data[i].app_name == this.$t('groupmanger.allWebsites')) {
            keyIndex = 'WEBSITE_';
            key = keyIndex + key;
          }
        }
        data[i].key = key;
        data[i].title = data[i].app_type || data[i].app_name;
        this.treeDataArr.push(key);
        if (parent) {
          data[i].parent = parent;
        }
        if (data[i].app_list) {
          data[i].children = data[i].app_list;
          this.dealMapTreeData(data[i].app_list, key, keyIndex);
        }
        this.treeApplyMaps[key] = data[i];
      }
    },

    //展开应用树节点
    onTreeExpand(expandedKeys) {
      this.applyTree.expandedKeys = expandedKeys;
      this.applyTree.autoExpandParent = false;
    },

    //选中应用树节点
    onTreeSelect(selectedKeys, info) {
      console.log('selectedKeys:', selectedKeys, 'onSelect:', info);
      const { checked, node } = info;
      const clickName = node._props.eventKey;
      if (checked) {
        this.selectApplyName.push(clickName);
      } else {
        const newSelectArr = selectedKeys.filter((item, index) => {
          // 遍历看每个字节的父节点是否被选中，如果选中，就移除自身
          let parent = this.treeApplyMaps[item]
            ? this.treeApplyMaps[item].parent
            : null;
          if (parent && selectedKeys.indexOf(parent) != -1) {
            //父元素也在列表中，该节点可以移除
            return false;
          }
          if (item == clickName) {
            return false;
          }
          return true;
        });
        this.selectApplyName = [...newSelectArr];
      }
    },

    //递归移除父节点
    recursionRemoveParents(node) {
      if (node.$parent.$vnode.key) {
        this.selectApplyName = this.selectApplyName.filter((item) => {
          return item != node.$parent.$vnode.key;
        });
        if (node.$parent.$vnode.key) {
          this.recursionRemoveParents(node.$parent);
        }
      }
    },

    getSelectApply() {
      this.selectApplyName.map((item) => {
        return item != '';
      });
      let selectApplyName = [...this.selectApplyName];
      //MACC包装的全部应用下发配置需要配置子节点
      if (selectApplyName.includes(this.$t('groupmanger.allApplications'))) {
        for (let i = 0; i < this.blockList.length; i++) {
          let item = this.blockList[i];
          selectApplyName.push(item.value);
        }
        selectApplyName = selectApplyName.filter(
          (x) => x !== this.$t('groupmanger.allApplications')
        );
      }
      //MACC包装的全部网站下发配置需要配置子节点
      if (
        selectApplyName.includes(
          `WEBSITE_${this.$t('groupmanger.allWebsites')}`
        ) ||
        selectApplyName.includes(`${this.$t('groupmanger.allWebsites')}`)
      ) {
        for (let i = 0; i < this.webSiteList.length; i++) {
          let item = this.webSiteList[i];
          if (
            this.policyType.indexOf('BLOCK') != -1 &&
            this.policyType.indexOf('WEBSITE') != -1
          ) {
            selectApplyName.push('WEBSITE_' + item.value);
          } else {
            selectApplyName.push(item.value);
          }
        }

        selectApplyName = selectApplyName.filter(
          (x) => x !== this.$t('groupmanger.allWebsites')
        );
        selectApplyName = selectApplyName.filter(
          (x) => x !== `WEBSITE_${this.$t('groupmanger.allWebsites')}`
        );
      }

      let newArr = [...new Set(selectApplyName)];
      return newArr;
    },

    fetchApply(val) {
      this.fetching = true;
      if (val == '') {
        this.searchData = [];
      } else {
        let val1 = val.toLowerCase();
        this.searchData = this.treeDataArr.filter((item) => {
          return item.toLowerCase().indexOf(val1) != -1;
        });
        this.fetching = false;
      }
    },

    //右侧选中的应用修改
    onListSelectChange(checkVal) {
      this.applyTree.selectedKeys = checkVal;
    },

    searchSelect(val) {
      this.applyTree.selectedKeys.push(val.key);
      this.selectApplyName.push(val.key);
      this.searchVal = undefined;
    },

    //重置
    restSelectApply() {
      this.applyTree.selectedKeys = [];
      this.applyTree = { ...this.applyTree };
      this.selectApplyName = [];
    },

    //刷新应用树
    async refreshApplyTree() {
      await this.getApplyTreeData();
      this.dealPolicyType();
    },
  },
};
</script>

<style lang="less" scoped>
.treeSelectWapper {
  background: #ffffff;
  box-shadow: 0px 2px 8px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  padding: 10px;
  display: flex;
  align-items: flex-start;
  justify-content: flex-start;
  height: 400px;
  .leftTreeWapper {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: flex-start;
    border: 1px solid #ececec;
    border-radius: 4px;
    flex: 3;
    margin-right: 10px;
    height: 100%;
    box-sizing: border-box;
    padding: 10px;
    .searchInput {
      width: 100%;
      box-sizing: border-box;
    }
    .allpyTree {
      height: 100%;
      box-sizing: border-box;
      overflow: auto;
      width: 100%;
    }
    .refreshWapper {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;
    }
    .loadingWapper {
      width: 100%;
      height: 100%;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  .rightSelectWapper {
    border: 1px solid #ececec;
    border-radius: 4px;
    flex: 2;
    height: 100%;
    overflow: auto;
    box-sizing: border-box;
    padding: 10px;
    /deep/ .ant-checkbox-group {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      justify-content: flex-start;
    }
    /deep/ .ant-checkbox-wrapper + .ant-checkbox-wrapper {
      margin-left: 0px;
    }
  }
}
</style>
